package com.sq.util.web;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Map;

import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;

/**
 * @author sq
 *
 */
public class HttpGetUtil extends BaseHttpUtil {


    public static String execute(String url) throws Exception {
        return execute(url, null);
    }

    public static String execute(String baseUrl, Map<String, String> params) throws Exception {
        return execute(baseUrl, params, null);
    }

    public static String execute(String baseUrl, Map<String, String> params, Map<String, String> headers)
            throws Exception {
        return execute(baseUrl, params, headers, StandardCharsets.UTF_8);
    }


    public static String execute(String baseUrl, Map<String, String> params, Map<String, String> headers,
                                 Charset charset) throws Exception {
        return execute(getHttpClient(), getRequestConfig(), baseUrl, params, headers, charset);
    }

    public static String execute(RequestConfig requestConfig, String url) throws Exception {
        return execute(requestConfig, url, null);
    }

    public static String execute(RequestConfig requestConfig, String baseUrl, Map<String, String> params) throws Exception {
        HttpGet httpGet = new HttpGet(genUrl(baseUrl, params));
        httpGet.setConfig(requestConfig);
        return request(getHttpClient(), httpGet, StandardCharsets.UTF_8);
    }

    public static String execute(RequestConfig requestConfig, String baseUrl, Map<String, String> params, Map<String, String> headers)
            throws Exception {
        return execute(requestConfig, baseUrl, params, headers, StandardCharsets.UTF_8);
    }

    public static String execute(RequestConfig requestConfig, String baseUrl, Map<String, String> params, Map<String, String> headers,
                                 Charset charset)
            throws Exception {
        return execute(getHttpClient(), requestConfig, baseUrl, params, headers, charset);
    }

    public static String execute(CloseableHttpClient httpClient, RequestConfig requestConfig, String baseUrl, Map<String, String> params, Map<String, String> headers,
                                 Charset charset) throws Exception {
        HttpGet httpGet = new HttpGet(genUrl(baseUrl, params));
        httpGet.setConfig(requestConfig);
        setHeaders(httpGet, headers);
        return request(httpClient, httpGet, charset);
    }


    private static String genUrl(String baseUrl, Map<String, String> params) {
        if (params == null) {
            return baseUrl;
        }
        if (params.isEmpty()) {
            return baseUrl;
        }
        return baseUrl + "?" + NetUtil.toFormFormat(params);
    }


}
